<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around w-full m-auto">
      <Select
        :options="selectOptions"
        style="width: 180px"
        v-model:value="currentCode"
        @change="handleSelected"
      />
      <a-button type="primary" @click="customSubmitFunc" class="ml-2">保存</a-button>
      <a-button type="primary" @click="handleDesign" class="ml-2" :disabled="isScriptEditable == 2"
        >设计器</a-button
      >
    </div>
    <div class="mt-2">
      <AceEditor
        v-model:value="scriptStr"
        :isReadonly="isScriptEditable > 0"
        style="height: 83vh"
      />
    </div>
  </ScrollContainer>
  <DesignIframe ref="ifrmRef" @register="registerDesignIframeView" @success="handleSuccess" />
</template>

<script lang="ts" setup>
  import { ref, unref, onUnmounted, onMounted, computed } from 'vue';
  import { ScrollContainer } from '/@/components/Container';
  import { Select } from 'ant-design-vue';
  import DesignIframe from './modules/DesignIframe.vue';
  import { useModal } from '/@/components/Modal';
  import { AceEditor } from '/@/components/AceEditor/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { useFlowStore } from '/@/store/modules/flow';
  import {
    getAdminFlowGetEventScript,
    getAdminFlowUpdateEventScriptByNode,
    getAdminFlowUpdateEventScriptByFlow,
  } from '/@/api/flowManage/flowManage';
  import { useMessage } from '/@/hooks/web/useMessage';

  const props = defineProps({
    typeCode: {
      type: String,
      default: '',
    },
    formCode: {
      type: String,
      default: '',
    },
  });
  const useFlow = useFlowStore();
  const { t } = useI18n();
  const userStore = useUserStore();

  const ifrmRef: any = ref(null);
  const scriptStr = ref('');
  const loading = ref(false);
  const currentCode = ref('onFinish');
  const { createMessage } = useMessage();
  const isScriptEditable = ref(0);

  const selectOptions = ref([
    {
      value: 'validate',
      label: '节点验证事件',
    },
    {
      value: 'preDispose',
      label: '节点预处理事件',
    },
    {
      value: 'actionActive',
      label: '节点激活事件',
    },
    {
      value: 'actionFinish',
      label: '节点流转事件',
    },
    {
      value: 'actionReturn',
      label: '节点退回事件',
    },
    {
      value: 'actionReturned',
      label: '节点被退回事件',
    },
    {
      value: 'preInit',
      label: '流程初始化事件',
    },
    {
      value: 'onFinish',
      label: '流程结束事件',
    },
    {
      value: 'discard',
      label: '流程放弃事件',
    },
    {
      value: 'recall',
      label: '流程撤回事件',
    },
    {
      value: 'deleteValidate',
      label: '删除流程验证事件',
    },
    // {
    //   value: 'form_js',
    //   label: '前台脚本(javascript)',
    // },
  ]);
  //节点事件
  const flowNodeArr = [
    'validate',
    'preDispose',
    'actionActive',
    'actionFinish',
    'actionReturn',
    'actionReturned',
  ];
  const [registerDesignIframeView, { openModal, closeModal }] = useModal();
  const customSubmitFunc = async () => {
    try {
      let values: any = {
        script: unref(scriptStr),
        typeCode: props.typeCode,
        eventType: unref(currentCode),
      };
      loading.value = true;
      console.log(values);
      if (flowNodeArr.includes(unref(currentCode))) {
        values.internalName = unref(flowInfo).curInternalName;
        //节点保存
        await getAdminFlowUpdateEventScriptByNode(values);
      } else {
        // 流程保存
        await getAdminFlowUpdateEventScriptByFlow(values);
      }
      getAdminFlowGetEventScriptData();
      createMessage.success(t('common.opSuccess'));
      loading.value = false;
    } catch (err) {
      console.log(err);
    } finally {
      loading.value = false;
    }
  };

  const getAdminFlowGetEventScriptData = async () => {
    if (!unref(currentCode)) {
      scriptStr.value = '';
      return;
    }
    const params: any = {
      typeCode: props.typeCode,
      eventType: unref(currentCode),
    };

    if (flowNodeArr.includes(unref(currentCode))) {
      params.internalName = unref(flowInfo).curInternalName;
    }
    const { script } = await getAdminFlowGetEventScript(params);
    scriptStr.value = script;
  };

  const flowInfo = computed(() => useFlow.flowInfo);
  const fetch = () => {
    console.log('flowInfo', flowInfo.value);
    if (!unref(flowInfo).curInternalName) {
      selectOptions.value = selectOptions.value.filter((_, index) => index > 5);
    } else {
      currentCode.value = 'validate';
      if (flowInfo.value.curAction?.getInDegree() == 0) {
        selectOptions.value = selectOptions.value.filter((_, index) => index != 4);
      }
    }
    getAdminFlowGetEventScriptData();

    let serverInfo = userStore.getServerInfo;
    isScriptEditable.value = serverInfo.isScriptEditable;
    console.log('isScriptEditable', isScriptEditable.value);
  };

  //change
  const handleSelected = () => {
    getAdminFlowGetEventScriptData();
  };

  onMounted(() => {
    fetch();
  });

  //设计器
  const handleDesign = () => {
    openModal(true, {
      scriptStr: unref(scriptStr),
      formCode: props.formCode,
    });
  };

  //回调
  const handleSuccess = (value) => {
    console.log('handleSuccess', value);
    if (value) {
      scriptStr.value = value;
    }
  };

  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      scriptStr.value = data;
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', scriptStr.value);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'flow.' + currentCode.value,
        data: scriptStr.value,
      };
      // window.postMessage(data, '*');
      unref(ifrmRef).doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }

  onUnmounted(() => {
    console.log('EventDesign-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });
</script>
